package com.lanlian.utillib;

import android.content.Context;
import android.view.WindowManager;

/**
 * 转换手机分辨率的类
 *
 * @author
 */
public class DisplayUtil {
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        int screenHeight = PreferencesUtils.getInt(context, "screenHeight", 0);
        if (screenHeight == 0) {
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            screenHeight = wm.getDefaultDisplay().getHeight();
            PreferencesUtils.putInt(context, "screenHeight", screenHeight);
        }
        return screenHeight;
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        int screenWidth = PreferencesUtils.getInt(context, "screenWidth", 0);
        if (screenWidth == 0) {
            WindowManager wm = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            screenWidth = wm.getDefaultDisplay().getWidth();
            PreferencesUtils.putInt(context, "screenWidth", screenWidth);
        }
        return screenWidth;
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = PreferencesUtils.getInt(context, "statusBarHeight", 0);
        if (statusBarHeight == 0) {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
            }
            PreferencesUtils.putInt(context, "statusBarHeight", statusBarHeight);
        }
        return statusBarHeight;
    }

}